<template>
  <div class="forgot-password-page">
    <div class="forgot-password-container">
      <!-- 左侧品牌区域 -->
      <div class="brand-section">
        <div class="brand-content">
          <div class="brand-logo">
            <el-icon :size="60" color="#409eff">
              <House />
            </el-icon>
          </div>
          <h1 class="brand-title">找回密码</h1>
          <p class="brand-subtitle">安全快速找回您的账户</p>
          <div class="brand-features">
            <div class="feature-item">
              <el-icon><Check /></el-icon>
              <span>安全验证</span>
            </div>
            <div class="feature-item">
              <el-icon><Message /></el-icon>
              <span>短信验证</span>
            </div>
            <div class="feature-item">
              <el-icon><Lock /></el-icon>
              <span>重设密码</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧重置表单 -->
      <div class="form-section">
        <div class="form-card">
          <!-- 步骤指示器 -->
          <div class="steps">
            <el-steps :active="currentStep" finish-status="success" simple>
              <el-step title="验证手机号"></el-step>
              <el-step title="设置新密码"></el-step>
              <el-step title="完成"></el-step>
            </el-steps>
          </div>

          <!-- 步骤1: 验证手机号 -->
          <div v-if="currentStep === 0" class="step-content">
            <div class="form-header">
              <h2>验证手机号</h2>
              <p>请输入您注册时使用的手机号</p>
              <!-- 返回首页按钮 -->
              <el-button 
                type="text" 
                @click="goToHome" 
                class="back-home-btn"
                style="margin-top: 10px; color: #409eff;"
              >
                <el-icon><ArrowLeft /></el-icon>
                返回首页
              </el-button>
            </div>

            <el-form 
              :model="verifyForm" 
              :rules="verifyRules" 
              ref="verifyFormRef"
              class="verify-form"
            >
              <el-form-item prop="mobile">
                <el-input
                  v-model="verifyForm.mobile"
                  placeholder="请输入手机号"
                  size="large"
                  clearable
                  maxlength="11"
                  @input="handleMobileInput"
                >
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="code">
                <div class="code-input">
                  <el-input
                    v-model="verifyForm.code"
                    placeholder="请输入6位验证码"
                    size="large"
                    clearable
                    maxlength="6"
                    @keyup.enter="handleVerify"
                  >
                    <template #prefix>
                      <el-icon><Message /></el-icon>
                    </template>
                  </el-input>
                  <el-button 
                    @click="sendCode" 
                    :disabled="countdown > 0 || !verifyForm.mobile || !/^1[3-9]\d{9}$/.test(verifyForm.mobile)"
                    class="code-btn"
                    size="large"
                    :loading="sendingCode"
                  >
                    {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
                  </el-button>
                </div>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  size="large"
                  :loading="loading"
                  @click="handleVerify"
                  class="verify-btn"
                >
                  验证并继续
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 步骤2: 设置新密码 -->
          <div v-if="currentStep === 1" class="step-content">
            <div class="form-header">
              <h2>设置新密码</h2>
              <p>请为您的账户设置新密码</p>
            </div>

            <el-form 
              :model="passwordForm" 
              :rules="passwordRules" 
              ref="passwordFormRef"
              class="password-form"
            >
              <el-form-item prop="password">
                <el-input
                  v-model="passwordForm.password"
                  type="password"
                  placeholder="请输入新密码（6-20位）"
                  size="large"
                  show-password
                  clearable
                  @input="checkPasswordStrength"
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
                <!-- 密码强度指示器 -->
                <div class="password-strength" v-if="passwordForm.password">
                  <div class="strength-bar">
                    <div 
                      class="strength-fill" 
                      :style="{ width: passwordStrength.width, backgroundColor: passwordStrength.color }"
                    ></div>
                  </div>
                  <span class="strength-text" :style="{ color: passwordStrength.color }">
                    {{ passwordStrength.text }}
                  </span>
                </div>
              </el-form-item>

              <el-form-item prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请确认新密码"
                  size="large"
                  show-password
                  clearable
                  @keyup.enter="handleResetPassword"
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  size="large"
                  :loading="loading"
                  @click="handleResetPassword"
                  class="reset-btn"
                >
                  重置密码
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 步骤3: 完成 -->
          <div v-if="currentStep === 2" class="step-content success-content">
            <div class="success-icon">
              <el-icon :size="80" color="#67c23a">
                <CircleCheck />
              </el-icon>
            </div>
            <h2>密码重置成功！</h2>
            <p>您的密码已成功重置，请使用新密码登录</p>
            
            <div class="success-actions">
              <el-button
                type="primary"
                size="large"
                @click="goToLogin"
                class="login-btn"
              >
                立即登录
              </el-button>
            </div>
          </div>

          <!-- 返回登录 -->
          <div class="form-footer" v-if="currentStep < 2">
            <div class="back-to-login">
              <span>想起密码了？</span>
              <router-link to="/login" class="login-link">返回登录</router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import {
  House,
  Check,
  Message,
  Lock,
  Phone,
  CircleCheck,
  ArrowLeft
} from '@element-plus/icons-vue'
import { authApi } from '@/services/api'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
const currentStep = ref(0)
const verifyFormRef = ref()
const passwordFormRef = ref()

// 验证手机号表单
const verifyForm = reactive({
  mobile: '',
  code: ''
})

// 密码重置表单
const passwordForm = reactive({
  password: '',
  confirmPassword: ''
})

// 密码强度
const passwordStrength = ref({
  width: '0%',
  color: '#909399',
  text: ''
})

// 表单验证规则
const verifyRules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理手机号输入
const handleMobileInput = (value) => {
  verifyForm.mobile = value.replace(/\D/g, '')
}

// 发送验证码
const sendCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(verifyForm.mobile)) {
    ElMessage.error('请输入正确的手机号')
    return
  }

  try {
    sendingCode.value = true
    
    // 调用发送验证码API
    await userStore.sendSmsCode(verifyForm.mobile)
    
    ElMessage.success('验证码已发送')
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
  } catch (error) {
    console.error('发送验证码失败:', error)
    if (error.response?.status === 403) {
      ElMessage.error('权限不足，无法发送验证码')
    } else if (error.response?.status === 429) {
      ElMessage.error('发送过于频繁，请稍后再试')
    } else if (error.response?.status === 404) {
      ElMessage.error('该手机号未注册')
    } else {
      ElMessage.error('发送验证码失败，请重试')
    }
  } finally {
    sendingCode.value = false
  }
}

// 验证手机号和验证码
const handleVerify = async () => {
  try {
    await verifyFormRef.value.validate()
    loading.value = true
    
    // 调用验证API
    await authApi.verifyResetCode({
      mobile: verifyForm.mobile,
      code: verifyForm.code
    })
    
    ElMessage.success('验证成功')
    currentStep.value = 1
    
  } catch (error) {
    if (error.errors) return // 表单验证错误
    console.error('验证失败:', error)
    
    if (error.response?.status === 401) {
      ElMessage.error('验证码错误或已过期')
    } else {
      ElMessage.error('验证失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 检查密码强度
const checkPasswordStrength = () => {
  const password = passwordForm.password
  let strength = 0
  let text = ''
  let color = '#909399'
  let width = '0%'

  if (password.length >= 6) strength++
  if (password.match(/[a-z]/)) strength++
  if (password.match(/[A-Z]/)) strength++
  if (password.match(/[0-9]/)) strength++
  if (password.match(/[^a-zA-Z0-9]/)) strength++

  switch (strength) {
    case 0:
    case 1:
      text = '弱'
      color = '#f56c6c'
      width = '25%'
      break
    case 2:
      text = '一般'
      color = '#e6a23c'
      width = '50%'
      break
    case 3:
      text = '良好'
      color = '#409eff'
      width = '75%'
      break
    case 4:
    case 5:
      text = '强'
      color = '#67c23a'
      width = '100%'
      break
  }

  passwordStrength.value = { width, color, text }
}

// 重置密码
const handleResetPassword = async () => {
  try {
    await passwordFormRef.value.validate()
    loading.value = true
    
    await authApi.resetPassword({
      mobile: verifyForm.mobile,
      code: verifyForm.code,
      password: passwordForm.password
    })
    
    ElMessage.success('密码重置成功')
    currentStep.value = 2
    
  } catch (error) {
    if (error.errors) return // 表单验证错误
    console.error('重置密码失败:', error)
    
    if (error.response?.status === 401) {
      ElMessage.error('验证码已过期，请重新获取')
    } else if (error.response?.status === 400) {
      ElMessage.error('密码格式不正确')
    } else {
      ElMessage.error('重置密码失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
}
</script>

<style scoped>
.forgot-password-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.forgot-password-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  max-width: 1000px;
  width: 100%;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: 600px;
}

.brand-section {
  background: linear-gradient(135deg, #409eff 0%, #536dfe 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 40px;
  position: relative;
  overflow: hidden;
}

.brand-section::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 1000'%3E%3Cg fill-opacity='0.03'%3E%3Cpolygon fill='%23fff' points='50 0 60 40 100 50 60 60 50 100 40 60 0 50 40 40'/%3E%3C/g%3E%3C/svg%3E") repeat;
  animation: float 20s infinite linear;
}

@keyframes float {
  0% { transform: translateY(0); }
  100% { transform: translateY(-100px); }
}

.brand-content {
  text-align: center;
  position: relative;
  z-index: 2;
}

.brand-logo {
  margin-bottom: 30px;
}

.brand-title {
  font-size: 2.5rem;
  font-weight: bold;
  margin: 0 0 15px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.brand-subtitle {
  font-size: 1.1rem;
  margin-bottom: 40px;
  opacity: 0.9;
}

.brand-features {
  display: grid;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 0.9rem;
}

.form-section {
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.steps {
  margin-bottom: 40px;
}

.step-content {
  min-height: 400px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 2rem;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.form-header p {
  color: #7f8c8d;
  margin: 0;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input .el-input {
  flex: 1;
}

.code-btn {
  white-space: nowrap;
  min-width: 110px;
}

.verify-btn,
.reset-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
  margin-top: 20px;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background-color: #e4e7ed;
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
  border-radius: 2px;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
}

.success-content {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.success-icon {
  margin-bottom: 30px;
}

.success-content h2 {
  font-size: 2rem;
  color: #2c3e50;
  margin: 0 0 15px 0;
  font-weight: 600;
}

.success-content p {
  color: #7f8c8d;
  margin-bottom: 30px;
  font-size: 1.1rem;
}

.login-btn {
  width: 200px;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
}

.form-footer {
  text-align: center;
  margin-top: 30px;
}

.back-to-login {
  font-size: 14px;
  color: #606266;
}

.login-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 5px;
}

.login-link:hover {
  text-decoration: underline;
}

.back-home-btn {
  margin-top: 10px;
  color: #409eff;
}

@media (max-width: 768px) {
  .forgot-password-container {
    grid-template-columns: 1fr;
    max-width: 400px;
  }

  .brand-section {
    display: none;
  }

  .form-section {
    padding: 40px 30px;
  }

  .form-header h2 {
    font-size: 1.5rem;
  }

  .code-input {
    flex-direction: column;
  }

  .code-btn {
    min-width: auto;
  }
}

@media (max-width: 480px) {
  .forgot-password-page {
    padding: 10px;
  }

  .form-section {
    padding: 30px 20px;
  }

  .step-content {
    min-height: 300px;
  }
}
</style> 